//
//  LMCommentController.m
//  EPA
//
//  Created by lanou3g on 16/4/26.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "LMCommentController.h"
#import "LMCommentModel.h"
#import "LMCommentCell.h"
#import "LMSendCOmmentController.h"
@interface LMCommentController ()
@property (nonatomic, strong) NSMutableArray *commentArray;
@end

@implementation LMCommentController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self didLoadData];
    self.tableView.backgroundColor =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"IMG_0106.JPG"]];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.commentArray = [NSMutableArray array];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"LMCommentCell" bundle:nil] forCellReuseIdentifier:@"LMCommentCell"];
    //    发表评论
    UIBarButtonItem *commentBtn  =  [[UIBarButtonItem alloc]initWithTitle:@"发表评论" style:UIBarButtonItemStylePlain target:self action:@selector(sendCommentBtnAction:)];
    self.navigationItem.rightBarButtonItem = commentBtn;
    [self didLoadData];
}

- (void)sendCommentBtnAction:(UIBarButtonItem *)item{
    
    if ([UserInfoManager shareManager].auth != nil) {
        LMSendCOmmentController *sendVC = [[LMSendCOmmentController alloc]init];
        sendVC.connentID = self.connentID;
        [self.navigationController pushViewController:sendVC animated:YES];
    }else{
        NSLog(@"没有登录");
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有登录，马上去登陆" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIStoryboard *storyboad = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *loginVC = [storyboad instantiateViewControllerWithIdentifier:@"Login"];
            [self presentViewController:loginVC animated:YES completion:nil];
        }];
        [alertC addAction:yesAction];
        
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:nil];
        [alertC addAction:noAction];
        
        [self presentViewController:alertC animated:YES completion:nil];
    }

}

#pragma mark -  解析数据
- (void)didLoadData{
    
    NSURL *url = [NSURL URLWithString:GETCOMMENT_url];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    [mRequest setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString string];
    if ([UserInfoManager shareManager].auth != nil) {
        bodyStr = [NSString stringWithFormat:@"auth=%@&client=1&contentid=%@&deviceid=6D4DD967-5EB2-40E2-A202-37E64F3BEA31&limit=10&start=0&version=3.0.6",[UserInfoManager shareManager].auth,self.connentID];
    }else{
        bodyStr = [NSString stringWithFormat:@"auth=%@&client=1&contentid=%@&deviceid=6D4DD967-5EB2-40E2-A202-37E64F3BEA31&limit=10&start=0&version=3.0.6",@"",self.connentID];
    }

    [mRequest setHTTPBody:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = jsonDict[@"data"];
            NSDictionary *listDict = dataDict[@"list"];
            for (NSDictionary *item in listDict) {
                LMCommentModel *model = [[LMCommentModel alloc]init];
                [model setValuesForKeysWithDictionary:item];
                [self.commentArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
            });
        }
    }];
    [dataTask resume];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LMCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LMCommentCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.4];

    cell.model = self.commentArray[indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    LMCommentModel *model = self.commentArray[indexPath.row];
    NSString *content = model.content;
    NSDictionary *dict = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};
    CGRect rect = [content boundingRectWithSize:CGSizeMake(304, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dict context:nil];
    return rect.size.height + 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
